<template>
  <div class="modal-content" @click.stop>
    <h3 class="modalTitle">{{ title }}</h3>
    <form class="studentForm" @submit.prevent="onSubmit">
      <input v-model="formData.id" type="hidden" class="studentIdToEdit" />

      <label for="studentName">Name</label>
      <input
        v-model="formData.name"
        type="text"
        name="name"
        class="studentName"
        required
      />

      <label for="studentGender">Gender</label>
      <select v-model="formData.gender" name="gender" class="studentGender" required>
        <option value="Male">Male</option>
        <option value="Female">Female</option>
      </select>

      <label for="studentHobbies">Hobbies</label>
      <input
        v-model="formData.hobbies"
        type="text"
        name="hobbies"
        class="studentHobbies"
        required
      />

      <label for="studentEmail">Email</label>
      <input
        v-model="formData.email"
        type="email"
        name="email"
        class="studentEmail"
        required
      />

      <label for="studentPhone">Phone</label>
      <input
        v-model="formData.phone"
        type="text"
        name="phone"
        class="studentPhone"
        required
      />

      <label for="studentAge">Age</label>
      <input v-model="formData.age" type="number" name="age" class="studentAge" required />

      <button type="submit" class="saveStudentBtn">
        保存信息
      </button>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue'
import { uniqueId } from 'lodash'
import { getNowDateTime } from '@/utils'

interface IStudent {
  id: string | number
  name: string
  gender: string
  hobbies: string
  email: string
  phone: string
  age: number | string
  create_at?: string
  update_at?: string
}

const props = defineProps<{
  student: IStudent | null
  isEditMode: boolean
  onSubmit: (student: IStudent) => void
  title: string // 添加 title prop
}>()

const formData = ref<IStudent>({
  id: '',
  age: '',
  email: '',
  gender: '',
  hobbies: '',
  name: '',
  phone: ''
})

// 初始化表单数据
if (props.student) {
  formData.value = { ...props.student }
} else if (props.isEditMode) {
  // 如果是编辑模式但没有传入 student，则初始化为空对象
  formData.value = {id:'5',name:'小号', gender: '男', hobbies: '睡觉', email: '143392', phone:'158279', age: '12'}
} else {
  // 如果是添加模式，生成新的 ID
  formData.value.id = uniqueId('newstu_')
}

// 提交表单
const emit = defineEmits(['submit'])

const onSubmit = () => {
  const newStudent: IStudent = {
    ...formData.value,
    create_at: props.student?.create_at || getNowDateTime(),
    update_at: getNowDateTime()
  }

  emit('submit', newStudent)
}
</script>

<style scoped>
/* 在这里添加样式 */
</style>